package com.compass.doctor.dialog

import android.annotation.SuppressLint
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.callback.OnScreenPrescriptionCallBack
import com.compass.doctor.databinding.DialogScreenPrescriptionBinding
import com.compass.doctor.ui.patient.adapter.DictionariesAdapter
import com.compass.doctor.ui.prescription.adapter.ScreenAdapter
import com.compass.framework.base.BaseDialog
import com.compass.framework.base.BaseDialogFragment
import com.compass.framework.constant.TIME_YEAR
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toBeanOrNull
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.model.Dictionaries
import com.compass.framework.model.ScreenTag
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.DateUtils
import com.compass.framework.utils.DateUtils.getZeroDay
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getColorFromResource
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog

/**
 * Description： 处方筛选
 * Date:2023/12/19 11:10
 */
@SuppressLint("NotifyDataSetChanged")
class ScreenPrescriptionDialog {
    class Builder(
        activity: FragmentActivity,
        private var dictionariesList: ArrayList<Dictionaries>,
        private var rxTime: ArrayList<ScreenTag>,
        private var onScreenPrescriptionCallBack: OnScreenPrescriptionCallBack
    ) : BaseDialogFragment.Builder<Builder>(activity) {

        private val mBinding: DialogScreenPrescriptionBinding =
            DialogScreenPrescriptionBinding.inflate(LayoutInflater.from(activity))

        private lateinit var dictionariesAdapter: DictionariesAdapter
        private lateinit var screenTimeAdapter: ScreenAdapter //处方时间adapter

        private var startDate: Long? = null
        private var endDate: Long? = null

        //当前选中的position
        private var mCurrentSelectPosition = 0

        init {

            initView()
            initOrderStatus()
            initPrescriptionTime()
        }

        private fun initView() {
            setContentView(mBinding.root)
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT)
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
            setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
            gravity = Gravity.BOTTOM
            dictionariesAdapter = DictionariesAdapter()
            screenTimeAdapter = ScreenAdapter(1)
            mBinding.tvCancel.onClick {
                dismiss()
            }
            dictionariesAdapter.onItemClickListener = { _, position ->
                dictionariesList[position].isSelect = !dictionariesList[position].isSelect
                dictionariesAdapter.setData(dictionariesList)
            }

            screenTimeAdapter.onItemClickListener = { _, position ->

                updateTabItem(position)
                mBinding.tvSelectionTime.visibility =
                    if (position == 3 && rxTime[position].isSelect) View.VISIBLE else View.GONE
                mBinding.llSelectionTime.visibility =
                    if (position == 3 && rxTime[position].isSelect) View.VISIBLE else View.GONE

                screenTimeAdapter.notifyDataSetChanged()
            }
            mBinding.tvStartDate.onClick {
                showStartDataDialog()
            }
            mBinding.tvEndDate.onClick {
                showEndDataDialog()
            }
            mBinding.tvReset.onClick {
                resetData()
            }
            mBinding.tvConfirm.onClick {
                val list = ArrayList<String>()
                for (item in dictionariesList) {
                    if (item.isSelect) list.add(item.value)
                }


                onScreenPrescriptionCallBack.onScreenPrescriptionSave(
                    list,
                    startDate,
                    endDate,
                    dictionariesList
                )
                dismiss()
            }
        }

        //订单状态
        private fun initOrderStatus() {

            mBinding.rcyState.apply {
                val dp5 = dpToPx(5)
                val layoutFelManager = FlexboxLayoutManager(context)
                layoutFelManager.flexWrap = FlexWrap.WRAP // 按正常方向换行
                layoutFelManager.flexDirection = FlexDirection.ROW // 水平方向
                layoutFelManager.justifyContent = JustifyContent.FLEX_START // 左对齐
                layoutManager = layoutFelManager
                addItemDecoration(NormalItemDecoration().apply {
                    setBounds(left = dp5, top = dp5, right = dp5, bottom = dp5)
                })
                adapter = dictionariesAdapter
            }
            dictionariesAdapter.setData(dictionariesList)

        }


        //开方事件
        private fun initPrescriptionTime() {
            mBinding.rcyDate.apply {
                val dp5 = dpToPx(5)
                layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
                addItemDecoration(NormalItemDecoration().apply {
                    setBounds(left = dp5, top = dp5, right = dp5, bottom = dp5)
                })
                adapter = screenTimeAdapter
            }
            for (i in rxTime.indices){
                if (rxTime[i].isSelect){
                    updateTabItem(i)
                }
            }
            screenTimeAdapter.setData(rxTime)

        }

        /**
         * 设置生日日期
         */
        private fun showStartDataDialog() {
            CardDatePickerDialog.builder(activity)
                .setTitle("开始时间" )
                .showBackNow(false)
                .setLabelText("年", "月", "日")
                .setMaxTime(System.currentTimeMillis())
                .setMinTime(System.currentTimeMillis()-TIME_YEAR*10)
                .setBackGroundModel(CardDatePickerDialog.STACK)
                .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY)
                .setThemeColor(getColorFromResource(R.color.color_0165b8))
                .setOnChoose { milliecond ->

                    startDate =getZeroDay(milliecond)
                    rxTime[3].startDate=startDate
                    mBinding.tvStartDate.text =
                        DateUtils.conversionTime(milliecond, DateUtils.FORMAT_THREE)

                }.build().show()
        }



        /**
         * 设置生日日期
         */
        private fun showEndDataDialog() {
            startDate?.let {

                CardDatePickerDialog.builder(activity)
                    .setTitle("结束时间")
                    .showBackNow(false)
                    .setLabelText("年", "月", "日")
                    .setMaxTime(System.currentTimeMillis())
                    .setMinTime(it)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY)
                    .setThemeColor(getColorFromResource(R.color.color_0165b8))
                    .setOnChoose { milliecond ->
                        endDate = milliecond
                        rxTime[3].endDate=endDate
                        mBinding.tvEndDate.text =
                            DateUtils.conversionTime(milliecond, DateUtils.FORMAT_THREE)
                    }.build().show()

            }?: kotlin.run {
                TipsToast.showTips("请先选择开始时间")
            }

        }


        /**
         * 更新Tab状态
         * @param position 选择的item
         */
        private fun updateTabItem(position: Int) {
            setData(position)
            if (mCurrentSelectPosition != position) {
                //更新上一条item
                val selectedItem = screenTimeAdapter.getItem(mCurrentSelectPosition)
                selectedItem?.let { it.isSelect = false }
                //更新当前item
                val newItem = screenTimeAdapter.getItem(position)
                newItem?.let { it.isSelect = true }

                mCurrentSelectPosition = position
                screenTimeAdapter.notifyDataSetChanged()

            } else {
                val item = screenTimeAdapter.getItem(position)
                item?.let {
                    it.isSelect = !it.isSelect
                    if (!it.isSelect){
                        startDate = null
                        endDate = null
                    }
                }
            }
        }

        private fun setData(position: Int) {
            when (position) {
                0 -> {
                    //本日时间
                    rxTime[position].startDate?.let {
                        startDate = it
                    } ?: kotlin.run {
                        startDate = DateUtils.getZeroToday()
                        rxTime[position].startDate=startDate
                    }

                    rxTime[position].endDate?.let {
                        endDate = it
                    } ?: kotlin.run {
                        endDate = DateUtils.getToday()
                        rxTime[position].endDate=endDate
                    }


                }

                1 -> {
                    //本周
                    rxTime[position].startDate?.let {
                        startDate = it
                    } ?: kotlin.run {
                        startDate = DateUtils.getWeekStart()
                        rxTime[position].startDate=startDate
                    }

                    rxTime[position].endDate?.let {
                        endDate = it
                    } ?: kotlin.run {
                        endDate = DateUtils.getToday()
                        rxTime[position].endDate=endDate
                    }
                }

                2 -> {
                    //本月
                    rxTime[position].startDate?.let {
                        startDate = it
                    } ?: kotlin.run {
                        startDate = DateUtils.getMonthStart()
                        rxTime[position].startDate=startDate
                    }

                    rxTime[position].endDate?.let {
                        endDate = it
                    } ?: kotlin.run {
                        endDate = DateUtils.getToday()
                        rxTime[position].endDate=endDate
                    }
                }

                3 -> {
                    mBinding.tvSelectionTime.visible()
                    mBinding.llSelectionTime.visible()
                    rxTime[position].startDate?.let {
                        startDate = it
                        mBinding.tvStartDate.text =
                            DateUtils.conversionTime(startDate, DateUtils.FORMAT_THREE)
                    }

                    rxTime[position].endDate?.let {
                        endDate = it
                        mBinding.tvEndDate.text =
                            DateUtils.conversionTime(endDate, DateUtils.FORMAT_THREE)
                    }
                }
            }

        }


        /**
         * 重置数据
         */

        private fun resetData() {
            startDate = null
            endDate = null
            for (item in dictionariesList) {
                item.isSelect = false
            }
            dictionariesAdapter.notifyDataSetChanged()
            for (item in rxTime) {
                item.isSelect = false
            }
            screenTimeAdapter.notifyDataSetChanged()
            mBinding.tvSelectionTime.gone()
            mBinding.llSelectionTime.gone()
        }


    }


}